import expressWs from 'express-ws'

import authRouter from '../routes/auth.js'
import sseRouter from '../routes/sse.js'
import testRouter from '../routes/test.js'
import wsRouter from '../routes/ws.js'
import {logger} from '../utils/logger.js'
import {getJwtAuthMiddleware} from '../middleware/jtwAuth.js'
import {getSessionMiddleware} from '../middleware/session.js'
import {Result} from './Result.js'

import type { Request, Response } from 'express'
export function useRoutes(app){
	app.use(getJwtAuthMiddleware())
	app.use(getSessionMiddleware())

	app.use('/auth', authRouter)
	app.use('/sse', sseRouter)
	app.use('/test', testRouter)
	app.use('/ws', wsRouter)

	expressWs(app)

	app.use((req: Request, res: Response) => {
		res.status(404).send(Result.notFound(null));
	});

	app.use((err, req, res, next) => {
		logger.error(err.stack);
		if (err.name === 'UnauthorizedError') {
			res.status(401).send(Result.unauthorized(err.message));
			return;
		}
		res.status(500).send(Result.coreFail(err.message));
	});
}
